<?php
function RepaymentNewTradeInrepay($deal,$repaylist,$platformNo,$post_url,$mchnt_user_id,$k_repay_key){
		set_time_limit(0);
		require_once APP_ROOT_PATH."system/libs/user.php";
		require_once APP_ROOT_PATH."app/Lib/deal.php";
		require_once APP_ROOT_PATH."app/Lib/common.php";
		
		$fee = 0;
		$k=0;
		
		
		$total_repay_money = 0;		//$detail['true_repay_money'];
		$total_self_money = 0; 		//$detail['true_self_money'];
		$total_impose_money = 0; 	//$detail['impose_money'];
		$total_manage_money = 0; 	//$detail['true_manage_money'];
		$total_mortgage_fee = 0; 	//$detail['true_mortgage_fee'];
		$total_true_manage_money_rebate = 0;

		foreach($repaylist as $k=>$v){
			$detail = array();
				
			//平台收取：借款者 的管理费 + 管理逾期罚息
			$detail['manage_fee'] = (float)$v['true_repay_manage_money'] + (float)$v['true_repay_manage_impose_money'] + (float)$v['true_mortgage_fee'];
				
			//==============================投资者获取的，费用===================================
			
			$detail['deal_id'] = $deal['id'];
			$detail['deal_repay_id'] = $v['repay_id'];
			$detail['deal_load_id'] = $v['load_id'];
			$detail['deal_load_repay_id'] = $v['id'];
			
			$temp_detail = $GLOBALS['db']->getRow("SELECT * FROM ".DB_PREFIX."fuioupay_cp_transaction_detail WHERE deal_repay_id=".$detail['deal_repay_id']." AND deal_id=".$detail['deal_id']." AND deal_load_id=".$detail['deal_load_id']." AND deal_load_repay_id=".$detail['deal_load_repay_id']);
			$mode = "";
			$where = "";
			if($temp_detail){
				$detail = $temp_detail;
				$mode = "UPDATE";
				$where = "id=".$temp_detail['id'];
			}
			else{
				$detail['is_callback'] = 0;
				$mode = "INSERT";
			}
			$detail['repay_manage_impose_money'] = (float)$v['true_repay_manage_impose_money'];//平台收取 借款者 的管理费逾期罚息
			$detail['impose_money'] = (float)$v['impose_money'];//投资者收取 借款者 的逾期罚息			
			$detail['repay_status'] = 0;//还款状态
			$detail['true_repay_time'] = TIME_UTC;//还款时间
			
			require_once APP_ROOT_PATH.'system/collocation/fuioupay/transferBu.php';
			
			//投资人会员编号
			
			//债权转让后,还款时，转给：承接者, 在债权转让后需要更新 fanwe_deal_load_repay.t_user_id 数据值
			$detail['user_id'] = $v['user_info']['user_id'];
			
		
			//投资者获取的，费用 [宝付会自动扣除 $detail['fee'] 部分，所以最终获得的收入为：$v['month_repay_money'] + $v['impose_money'] - $v['manage_money'] - $v['manage_interest_money']
			$detail['amount'] = round((float)$v['true_repay_money'] + (float)$v['impose_money'],2);
		
			//平台收取：投资者 的投资金额管理费 + 利息管理费
			$detail['fee'] = round((float)$v['true_manage_money']+(float)$v['true_manage_interest_money'],2);
				
			$GLOBALS['db']->autoExecute(DB_PREFIX."fuioupay_cp_transaction_detail",$detail,$mode,$where);
			
			if($mode=="INSERT"){
				$detail_id = $GLOBALS['db']->insert_id();
			}else{
				$detail_id = $temp_detail['id'];
			}
			
			//转账
			if($detail['is_callback'] == 0){
				$rs = transferBu($detail['user_id'],$deal['user_id'],$detail['amount'],$platformNo,$post_url,$deal['id']);
				if($rs['resp_code']=="0000"){
					$detail['is_callback'] = 1;
					$GLOBALS['db']->query("UPDATE  ".DB_PREFIX."fuioupay_cp_transaction_detail SET is_callback=1 WHERE id=".$detail_id);
				}
			}
			//管理费 - 投资者
			if($detail['is_callback'] == 1){
				if($detail['fee'] != 0)
					$rs = transferBu($mchnt_user_id,$detail['user_id'],$detail['fee'],$platformNo,$post_url,$deal['id']);
				if($rs['resp_code']=="0000"|| $detail['fee'] ==0){
					$detail['is_callback'] = 2;
					$GLOBALS['db']->query("UPDATE  ".DB_PREFIX."fuioupay_cp_transaction_detail SET is_callback=2 WHERE id=".$detail_id);
				}
			}
			//管理费 - 借款人
			if($detail['is_callback'] == 2){
				if($detail['manage_fee'] != 0)
					$rs = transferBu($mchnt_user_id,$deal['user_id'],$detail['manage_fee'],$platformNo,$post_url,$deal['id']);
				if($rs['resp_code']=="0000" || $detail['manage_fee'] ==0){
					$detail['is_callback'] = 3;
					$GLOBALS['db']->query("UPDATE  ".DB_PREFIX."fuioupay_cp_transaction_detail SET is_callback=3 WHERE id=".$detail_id);
				}
			}
			//print_r($v);die();
			
			if($detail['is_callback'] == 3){
				$load_repay = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."deal_load_repay where repay_id= ".$detail['deal_repay_id']." AND  id = ".$v['id']);
				
				//repay_status,repay_manage_impose_money							
		
				$detail = array();
				$detail['repay_manage_impose_money'] = $v["repay_manage_impose_money"];//平台收取 借款者 的管理费逾期罚息
				$detail['impose_money'] = $v["impose_money"];//投资者收取 借款者 的逾期罚息
				$detail['status'] = 0;//还款状态
				$detail['true_repay_time'] = $v["true_repay_time"];//还款时间
				$detail['true_repay_date'] = to_date($v["true_repay_time"]);
					
					
				$detail['has_repay'] = 1;//0未收到还款，1已收到还款
				$detail['true_manage_money'] = round((float)$v['true_manage_money'],2);
	            $detail['true_mortgage_fee'] = round((float)$v['true_mortgage_fee'],2);
				$detail['true_manage_interest_money'] = round((float)$v['true_manage_interest_money'],2);
				$detail['true_repay_manage_money'] = round((float)$v["true_repay_manage_money"],2);
				$detail['true_repay_money'] = round((float)$v["true_repay_money"],2);
				$detail['true_self_money'] = round((float)$v['true_self_money'],2);
				$detail['true_interest_money'] =  round((float)$v['true_interest_money'],2);
				$detail['true_reward_money'] = round((float)$v['true_reward_money'],2);
				$detail['true_interestrate_money']= round((float)$v['true_interestrate_money'],2);
		
				$GLOBALS['db']->autoExecute(DB_PREFIX."deal_load_repay",$detail,'UPDATE'," has_repay = 0 and id = ".intval($v['id']));
				
				if($GLOBALS['db']->affected_rows() > 0){
					
					$total_true_manage_money_rebate += $v['true_manage_money_rebate'];

					//会员分销返利
//					get_distribution_referrals($v['id']);
					
					
					//短信通知回款
					$v['user_info']  = get_user("*",intval($v['user_info']['user_id']));
					
					$v['user_info']['user_id']  = $v['user_info']['user_id'];
					
					$deal = get_deal(intval($load_repay['deal_id']));
					
					$kk = $load_repay['l_key'];
					
					//更新用户账户资金记录
					/*modify_account(array("money"=>$detail['true_repay_money']),$v['user_info']['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],提前回款,收到本金：".$detail['true_self_money']."，利息：".$detail['true_interest_money']."，总额：".$detail['true_repay_money'],5,1);
					
					if($detail['true_manage_money'] > 0)
						modify_account(array("money"=>-$detail['true_manage_money']),$v['user_info']['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],提前还款投标管理费",20,1);
		            
					//利息管理费
					if($detail['true_manage_interest_money']!=0)
						modify_account(array("money"=>-$detail['true_manage_interest_money']),$v['user_info']['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],提前还款投标利息管理费",20,1);
						
					if($detail['impose_money'] != 0)
						modify_account(array("money"=>$detail['impose_money']),$v['user_info']['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],提前还款违约金",21,1);
					*/
					
					$total_repay_money += $detail['true_repay_money'];		//$detail['true_repay_money'];
					$total_self_money += $detail['true_self_money']; 		//$detail['true_self_money'];
					$total_impose_money += $detail['impose_money']; 	//$detail['impose_money'];
					$total_manage_money += $detail['true_repay_manage_money']; 	//$detail['true_manage_money'];
					$total_mortgage_fee += $detail['true_mortgage_fee']; 	//$detail['true_mortgage_fee'];
					
					//投资者奖励 - 加息券
					if($detail['true_interestrate_money']!=0){
						
						//$in_data = array();
						//$in_data['user_id'] = $v['user_info']['id'];
						
						/*$rs = transferBu($v['user_info']['id'],$mchnt_user_id,$detail['true_interestrate_money'],$platformNo,$post_url,$deal['id'],0,53,"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],提前还款加息券收益");
						if($rs['resp_code']=="0000"){
						*/ 
							//$in_data['status'] = 1;
							//$in_data['pay_time'] = to_date(TIME_UTC);
						//	$old_user_id=$GLOBALS['db']->getOne("select user_id from ".DB_PREFIX."deal_load where id=".$v['load_id']);
						//	modify_account(array("money"=>$detail['true_interestrate_money']),$old_user_id,"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],提前还款加息券收益",53);
						/*}
						else{
						//	$in_data['status'] = 0;
						}*/
						
						//$in_data['info'] = "[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],提前还款加息券收益";
						//$in_data['money'] = $detail['true_interestrate_money'];
						
						//$GLOBALS['db']->autoExecute(DB_PREFIX."deal_interestrate_money",$in_data);
					}
					
					//投资者奖励
					if($detail['true_reward_money']!=0){
						$rs = transferBu($v['user_info']['id'],$mchnt_user_id,$detail['true_reward_money'],$platformNo,$post_url,$deal['id'],0,28,"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],提前还款投标奖励");
						//if($rs['resp_code']=="0000")
							//modify_account(array("money"=>$detail['true_reward_money']),$v['user_info']['id'],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],提前还款投标奖励",28,1);
					}
					
					
					$GLOBALS['db']->query("UPDATE ".DB_PREFIX."deal_load_repay set has_repay=1,status=1 where deal_id=".$deal['id']." AND l_key>".$k_repay_key); 
				
					
					$load_repay_rs = $GLOBALS['db']->getRow("SELECT (sum(true_interest_money) + sum(impose_money)) as shouyi,sum(impose_money) as total_impose_money FROM ".DB_PREFIX."deal_load_repay WHERE id=".$load_repay['id']);
					$all_shouyi_money= number_format($load_repay_rs['shouyi'],2);
					$all_impose_money = number_format($load_repay_rs['total_impose_money'],2);
					
					//更新用户回款计划
					syn_deal_repay_status($deal['id'],$load_repay['repay_id']);
					
					//投资者返佣金
					if(floatval($v['true_manage_interest_money_rebate'])!=0){
						/*ok*/
						$reback_memo = "借款“<a href'".$deal['url']."'>".$deal["name"]."</a>”,投资者".$v['user_info']["user_name"]."，第".(intval($kk)+1)."期,提前还款";
						reback_rebate_money($v['user_info']['user_id'],$v['true_manage_interest_money_rebate'],"invest",$reback_memo);
					}
					$time = TIME_UTC;
					$msg_conf = get_user_msg_conf($v['user_info']['user_id']);
					//短信通知
					if(app_conf("SMS_ON")==1&&app_conf('SMS_REPAY_TOUSER_ON')==1){
							
						$tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_DEAL_LOAD_REPAY_SMS'",false);
						$tmpl_content = $tmpl['content'];
							
						$notice['user_name'] = $v['user_info']['user_name'];
						$notice['deal_name'] = $deal['sub_name'];
						$notice['deal_url'] = $deal['url'];
						$notice['site_name'] = app_conf("SHOP_TITLE");
						$notice['repay_money'] = round($detail['true_repay_money']+$detail['impose_money'],2);
							
						$notice['all_repay_money'] = $all_repay_money;
						$notice['impose_money'] = $all_impose_money;
							
						$GLOBALS['tmpl']->assign("notice",$notice);
						$sms_content = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
							
						$msg_data['dest'] = $v['user_info']['mobile'];
						$msg_data['send_type'] = 0;
						$msg_data['title'] = $msg_data['content'] = addslashes($sms_content);
						$msg_data['send_time'] = 0;
						$msg_data['is_send'] = 0;
						$msg_data['create_time'] = $time;
						$msg_data['user_id'] = $v['user_info']['user_id'];
						$msg_data['is_html'] = 0;
						$GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
					}
					
					//回款通知
					if(app_conf("WEIXIN_MSG")==1){
						$user_info = get_user_info("*","id = ".$v['user_info']['user_id']);
						if($user_info['wx_openid']!='')
						{
							$tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."weixin_tmpl where template_id_short='OPENTM207940989' ");
							$repay_money = number_format(round($detail['true_repay_money']+$detail['impose_money'],2),2);
							$weixin_data['first'] = array('value'=>'投标回款短信通知','color'=>'#173177');
							$weixin_data['keyword1']=array('value'=>$deal['sub_name'],'color'=>'#173177');
							$weixin_data['keyword2']=array('value'=>$v['user_info']['user_name'],'color'=>'#173177');
							$weixin_data['keyword3']=array('value'=>$repay_money,'color'=>'#173177');
							weixin_tmpl_send($tmpl['template_id'],$v['user_info']['user_id'],$weixin_data);
						}
					}
					//站内信
					
					$notices['shop_title'] = app_conf("SHOP_TITLE");
					$notices['url'] = "“<a href=\"".$deal['url']."\">".$deal['name']."</a>”";
					$notices['repay_money'] = $all_repay_money;
					$notices['impose_money'] = $all_impose_money;
					
					$tmpl_contents = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_REPAY_MONEY_TQTB'",false);
					$GLOBALS['tmpl']->assign("notice",$notices);
					$content = $GLOBALS['tmpl']->fetch("str:".$tmpl_contents['content']);
					
					if($msg_conf['sms_bidrepaid']==1)
						send_user_msg("",$content,0,$v['user_info']['user_id'],$time,0,true,9);
					//邮件
					if($msg_conf['mail_bidrepaid']==1 && app_conf('MAIL_ON')==1){
						
						$tmpl = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."msg_template where name = 'TPL_DEAL_LOAD_REPAY_EMAIL'",false);
						$tmpl_content = $tmpl['content'];
							
						$notice['user_name'] = $v['user_info']['user_name'];
						$notice['deal_name'] = $deal['sub_name'];
						$notice['deal_url'] = $deal['url'];
						$notice['site_name'] = app_conf("SHOP_TITLE");
						$notice['site_url'] = SITE_DOMAIN.APP_ROOT;
						$notice['help_url'] = SITE_DOMAIN.url("index","helpcenter");
						$notice['msg_cof_setting_url'] = SITE_DOMAIN.url("index","uc_msg#setting");
						$notice['repay_money'] = round($detail['true_repay_money']+$detail['impose_money'],2);
							
						$notice['all_repay_money'] = $all_repay_money;
						$notice['impose_money'] = $all_impose_money;
							
						$GLOBALS['tmpl']->assign("notice",$notice);
							
						$msg = $GLOBALS['tmpl']->fetch("str:".$tmpl_content);
						$msg_data['dest'] = $v['user_info']['email'];
						$msg_data['send_type'] = 1;
						$msg_data['title'] = "“".$deal['name']."”回款通知";
						$msg_data['content'] = addslashes($msg);
						$msg_data['send_time'] = 0;
						$msg_data['is_send'] = 0;
						$msg_data['create_time'] = $time;
						$msg_data['user_id'] = $v['user_info']['user_id'];
						$msg_data['is_html'] = $tmpl['is_html'];
						$GLOBALS['db']->autoExecute(DB_PREFIX."deal_msg_list",$msg_data); //插入
					}
				}
			}
		}
		
		$inrepay_data = array();
		//录入到提前还款列表
		$inrepay_data['deal_id'] = $deal['id'];
		$inrepay_data['user_id'] = $deal["user_id"];		//;$GLOBALS['user_info']['id'];
		$inrepay_data['repay_money'] = $total_repay_money;		//$detail['true_repay_money'];
		$inrepay_data['self_money'] = $total_self_money; 		//$detail['true_self_money'];
		$inrepay_data['impose_money'] = $total_impose_money; 	//$detail['impose_money'];
		$inrepay_data['manage_money'] = $total_manage_money; 	//$detail['true_manage_money'];
		$inrepay_data['mortgage_fee'] = $total_mortgage_fee; 	//$detail['true_mortgage_fee'];
		$inrepay_data['repay_time'] = $k_repay_time;
		$inrepay_data['true_repay_time'] = TIME_UTC;
		
		/*
		//录入到提前还款列表
		$inrepay_data['deal_id'] = $load_repay['deal_id'];
		$inrepay_data['user_id'] = $GLOBALS['user_info']['id'];
		$inrepay_data['repay_money'] = $detail['true_repay_money'];
		$inrepay_data['self_money'] = $detail['true_self_money'];
		$inrepay_data['impose_money'] = $detail['impose_money'];
		$inrepay_data['manage_money'] = $detail['true_repay_manage_money'];
		$inrepay_data['mortgage_fee'] = $detail['true_mortgage_fee'];
		$inrepay_data['repay_time'] = $k_repay_time;
		$inrepay_data['true_repay_time'] = $detail['true_repay_time'];
		*/
		$GLOBALS['db']->autoExecute(DB_PREFIX."deal_inrepay_repay",$inrepay_data,"INSERT");
		
		$GLOBALS['db']->query("UPDATE ".DB_PREFIX."deal_load_repay set has_repay = 1 , status=0,true_repay_time = '".TIME_UTC."',true_repay_date='".to_date(TIME_UTC)."' where deal_id=".$deal['id']." AND l_key>=".intval($k_repay_key));
				
		$GLOBALS['db']->query("UPDATE ".DB_PREFIX."deal_repay set has_repay = 1 , status=0,true_repay_time = '".TIME_UTC."',true_repay_date='".to_date(TIME_UTC)."' where deal_id=".$deal['id']." AND l_key>=".intval($k_repay_key));
		
		//借款人start
		/*modify_account(array("money"=>-round($inrepay_data['impose_money'],2)),$deal["user_id"],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],提前还款违约金",6,1);
		modify_account(array("money"=>-round($inrepay_data['manage_money'],2)),$deal["user_id"],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],提前还款管理费",10,1);
		modify_account(array("money"=>-round($inrepay_data['mortgage_fee'],2)),$deal["user_id"],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],提前还款抵押物管理费",27,1);
		modify_account(array("money"=>-round($inrepay_data['repay_money'],2)),$deal["user_id"],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],提前还款本息",6,1);
		//用户获得额度
		modify_account(array("quota"=>trim(app_conf('USER_REPAY_QUOTA'))),$deal["user_id"],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],还清借款获得额度",6,1);
*/
		//借款者返佣金
		if($total_true_manage_money_rebate!=0){
			/*ok*/
			$reback_memo = '借款“<a href="'.$deal["url"].'">'.$deal["name"].'</a>”，借款者'.$deal["user"]["user_name"];
			reback_rebate_money($deal["user_id"],$total_true_manage_money_rebate,"borrow",$reback_memo);
		}
		
		
		//判断获取的信用是否超过限制
		if($GLOBALS['db']->getOne("SELECT sum(point) FROM ".DB_PREFIX."user_point_log WHERE `type`=6 AND user_id=".$deal["user_id"]) < (int)trim(app_conf('REPAY_SUCCESS_LIMIT'))){
			//获取上一次还款时间
			$befor_repay_time = $GLOBALS['db']->getOne("SELECT MAX(create_time) FROM ".DB_PREFIX."user_point_log WHERE `type`=6 AND user_id=".$deal["user_id"]);
			$day = ceil(($time-$befor_repay_time)/24/3600);
			//当天数大于等于间隔时间 获得信用
			/*if($day >= (int)trim(app_conf('REPAY_SUCCESS_DAY'))){
				modify_account(array("point"=>trim(app_conf('REPAY_SUCCESS_POINT'))),$deal["user_id"],"[<a href='".$deal['url']."' target='_blank'>".$deal['name']."</a>],还清借款",6,1);
			}*/
		}
		
		//借款人end
		return json_encode(array("status"=>1 ,"deal_id"=>$deal['id'], "info" =>'已还款'));
}
